package admin.servlet;

import admin.dao.Addao;
import admin.entity.Adenty;
import admin.utils.JBDCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;


@WebServlet("/dologin")
public class dologin extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 接收前台传来的值 账号和密码
        String incid = req.getParameter("incid");
        String incpwd = req.getParameter("incpwd");
        System.out.println("输入的账号:"+incid);
        System.out.println("输入的密码"+incpwd);

        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        // 账号密码登录的方式
        if (incid != null && incpwd != null) {
            //解决中文字符乱码
            byte[] bytes = incid.getBytes("ISO-8859-1");
            incid = new String(bytes, "utf-8");
            System.out.println("转译后账号:"+incid);

            JBDCUtil db = new JBDCUtil();
            // 创建一个用户保存下将密码和用户名保存
            Adenty adenty = new Adenty(incid,incpwd);
            Addao dao = new Addao();
            try {
                //数据库连接
                Connection conn = db.getConn();
                if (dao.login(conn, adenty) != null) {
                    System.out.println("登录账号:"+dao.login(conn,adenty));
                    req.getSession().setAttribute("adenty", adenty);
                    resp.sendRedirect("success.jsp");
                } else {
                    out.println("<h1>用户名或者密码错误，验证失败</h1>");
                    out.println("<h2>3秒以后跳转回登录页面</h2>");
                    resp.setHeader("Refresh", "3;url=login.jsp");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                out.close();
            }
        }else { // 验证成功
            resp.sendRedirect("success.jsp");
        }
        out.close();
    }
}
